package aquarium.view;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oracle.jdbc.OracleResultSet;

import oracle.ord.im.OrdImage;


public class ImageLoader extends HttpServlet {
    private static final String CONTENT_TYPE = "image/jpeg; charset=utf-8";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        String imageId = request.getParameter("id");
        OutputStream os = response.getOutputStream();
        Connection conn = null;
        OrdImage imageOrd = null;
        try {
            Context ctx = new InitialContext();
            conn = getOracleConnection();
            Statement statement = conn.createStatement();
            StringBuilder query = new StringBuilder();
            query.append("SELECT fp_image,fp_id_picture ");
            query.append("FROM fish_photos ");
            query.append("WHERE fp_id_picture = ");
            query.append(imageId);

            OracleResultSet rs = (OracleResultSet)statement.executeQuery(query.toString());

            if (rs.next()) {
                imageOrd = (OrdImage)rs.getORAData(1, OrdImage.getORADataFactory());
                imageOrd.setProperties();
                BufferedInputStream in = new BufferedInputStream(imageOrd.getDataInStream());
                int b;
                byte[] buffer = new byte[20240];
                while ((b = in.read(buffer, 0, 20240)) != -1) {
                    os.write(buffer, 0, b);
                }
                os.close();
            }

            response.setContentType(imageOrd != null ? imageOrd.getMimeType() : CONTENT_TYPE);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException sqle) {
                System.out.println("SQLException error");
            }
        }


    }

    public static Connection getOracleConnection() throws Exception {
        String driver = "oracle.jdbc.driver.OracleDriver";
        String url = "jdbc:oracle:thin:@localhost:1521:orcl";
        String username = "aquarium";
        String password = "aquarium";

        Class.forName(driver); // load Oracle driver
        Connection conn = DriverManager.getConnection(url, username, password);
        return conn;
    }

}
